package v1

import (
	"sweetsunnyflower/app/models/chat"
	"sweetsunnyflower/app/policies"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/response"

	"github.com/gin-gonic/gin"
)

type ChatsController struct {
	Controller
}

func (ctrl *ChatsController) Index(c *gin.Context) {
	request := requests.ChatsQueryRequest{}
	if ok := requests.Validate(c, &request, requests.ChatsQuery); !ok {
		return
	}

	chats := chat.GetByLatestId(request)

	response.Data(c, chats)
}

func (ctrl *ChatsController) Show(c *gin.Context) {
	chatModel := chat.Get(c.Param("id"))
	if chatModel.ID == 0 {
		response.Abort404(c)
		return
	}
	response.Data(c, chatModel)
}

func (ctrl *ChatsController) Store(c *gin.Context) {

	request := requests.ChatRequest{}
	if ok := requests.Validate(c, &request, requests.ChatSave); !ok {
		return
	}

	chatModel := chat.Chat{
		// FieldName:      request.FieldName,
	}
	chatModel.Create()
	if chatModel.ID > 0 {
		response.Created(c, chatModel)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}

func (ctrl *ChatsController) Update(c *gin.Context) {

	chatModel := chat.Get(c.Param("id"))
	if chatModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyChat(c, chatModel); !ok {
		response.Abort403(c)
		return
	}

	request := requests.ChatRequest{}
	if ok := requests.Validate(c, &request, requests.ChatSave); !ok {
		return
	}

	// chatModel.FieldName = request.FieldName
	rowsAffected := chatModel.Save()
	if rowsAffected > 0 {
		response.Data(c, chatModel)
	} else {
		response.Abort500(c, "更新失败，请稍后尝试~")
	}
}

func (ctrl *ChatsController) Delete(c *gin.Context) {

	chatModel := chat.Get(c.Param("id"))
	if chatModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyChat(c, chatModel); !ok {
		response.Abort403(c)
		return
	}

	rowsAffected := chatModel.Delete()
	if rowsAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败，请稍后尝试~")
}
